//
//  ITAudioTool.m
//  ITBE
//
//  Created by ITBE on 2019/3/6.
//  Copyright © 2019 ITBE. All rights reserved.
//

#import "ITAudioTool.h"
#import <AVFoundation/AVFoundation.h>

@interface ITAudioTool()
{
    
}
@end
@implementation ITAudioTool
static NSMutableDictionary *_musices;
 +(NSMutableDictionary *)musices
{
    if (_musices==nil) {
        _musices=[NSMutableDictionary dictionary];
    }
    return _musices;
}

void playCallback(SystemSoundID ssID, void* __nullable clientData) {
    AudioServicesDisposeSystemSoundID(ssID);
//    CFRelease(clientData);//是播放声音时，放入的任意参数。
//    CFRunLoopStop(CFRunLoopGetCurrent());
}


+ (void)playSound{
    
    SystemSoundID sound;
    //NSString*path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"sms-received1",@"caf"];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"push_sound" ofType:@"mp3"];
    OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);

    if(error!=kAudioServicesNoError) {
        sound=0;
    }
    AudioServicesPlaySystemSound(sound);
    [self impactFeedback];
}

+(BOOL)playAudio:(NSString *)fileName
{
    if (!fileName) return NO;//如果没有传入文件名，那么直接返回
         //1.取出对应的播放器
    AVAudioPlayer *player= [self musices][fileName];
    
     //2.如果播放器没有创建，那么就进行初始化
     if (!player) {
         //2.1音频文件的URL
         NSURL *url= [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
         if (!url) return NO;//如果url为空，那么直接返回

         //2.2创建播放器
         player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

         //2.3缓冲
         if (![player prepareToPlay]) return NO;//如果缓冲失败，那么就直接返回

         //2.4存入字典
         [self musices][fileName]=player;
     }
    
     //3.播放
     if (![player isPlaying]) {
        //如果当前没处于播放状态，那么就播放
         return [player play];
     }

    return YES;//正在播放，那么就返回YES
}

+(void)pauseAudio:(NSString *)fileName
{
    if (!fileName) return;//如果没有传入文件名，那么就直接返回
     //1.取出对应的播放器
     AVAudioPlayer *player=[self musices][fileName];

     //2.暂停
     [player pause];//如果palyer为空，那相当于[nil pause]，因此这里可以不用做处理
}

+(void)stopAudio:(NSString *)fileName
{
    if (!fileName) return;//如果没有传入文件名，那么就直接返回
    
     //1.取出对应的播放器
     AVAudioPlayer *player=[self musices][fileName];

     //2.停止
     [player stop];

     //3.将播放器从字典中移除
     [[self musices] removeObjectForKey:fileName];
}

/**
 在需要出发震动的地方写上代码：
 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//默认震动效果

 如果想要其他震动效果，可参考：
 // 普通短震，3D Touch 中 Pop 震动反馈
 AudioServicesPlaySystemSound(1520);

 // 普通短震，3D Touch 中 Peek 震动反馈
 AudioServicesPlaySystemSound(1519);

 // 连续三次短震
 AudioServicesPlaySystemSound(1521);

 */

+ (BOOL)impactFeedback{
    if ([self canImpactFeedback]) {
        if (@available(iOS 10.0, *)){
            MainDelay(0, ^{
                UIImpactFeedbackGenerator*impactLight = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
                [impactLight impactOccurred];
            });
            return YES;
        }
    }
    return NO;
}

+ (void)vibrate{
    if ([self impactFeedback]) {
        return;
    }else if (@available(iOS 9.0, *)){
        if ([AppUtils findRootController].traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
            AudioServicesPlaySystemSound(1520);
            return;
        }
    }
    //默认震动比较大
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

+ (BOOL)canImpactFeedback{
    if (@available(iOS 10.0, *)) {
        NSString *model = [UIDevice currentDevice].machineModel;
        if ([model hasPrefix:@"iPhone"]) {
            model = [model safeSubstringFromIndex:6];
            NSArray *arr = [model componentsSeparatedByString:@","];
            if ([arr.firstObject intValue] >= 9) {
                return YES;
            }
        }
    }
    return NO;
}

@end
